package cn.shujuhai.cms.service.thymeleaf;

import cn.dev33.satoken.stp.StpUtil;
import cn.shujuhai.cms.config.TemplateEngineConfig;
import cn.shujuhai.cms.domain.InfoArticle;
import cn.shujuhai.cms.domain.SysChannel;
import cn.shujuhai.cms.service.InfoArticleService;
import cn.shujuhai.cms.service.SysChannelService;
import cn.shujuhai.cms.service.SysTemplateService;
import cn.shujuhai.common.mapper.SysUserMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.List;

/**
 * @Author: zhangDeZhong
 * @Date: 2024/12/5 12:01
 * @Description: 提供信息文章模板访问的Service实现
 **/
@Service
@RequiredArgsConstructor
public class InfoService {
    private final TemplateEngineConfig templateEngine;
    private final SysChannelService sysChannelService;
    private final SysTemplateService sysTemplateService;
    private final ChannelTool channelTool;
    private final InfoTool infoTool;
    private final SysTool sysTool;
    private final InfoArticleService infoArticleService;
    private final SysUserMapper sysUserMapper;


    @Value("${server.servlet.context-path}")
    private String base;

    private final static String infoCode = "info_admin";
    private final StaticHtmlService staticHtmlService;


    /**
     * 根据栏目的url和文章ID渲染相应的模板
     *
     * @param url       栏目路径
     * @param articleId 文章ID
     * @return 渲染后的模板内容
     */
    public String getInfo(String url, Long articleId) {
        SysChannel sysChannel = this.sysChannelService.getOne(Wrappers.<SysChannel>lambdaQuery().eq(SysChannel::getUrlKey, url));
        if (sysChannel == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "页面不存在！");
        }
        InfoArticle infoArticle = this.infoArticleService.getById(articleId);
        if (infoArticle == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "页面不存在！");
        }
        boolean flag = true;
        if (StpUtil.isLogin()) {
            List<String> permissionCodeList = sysUserMapper.selectPermissionCodesByUserId(StpUtil.getLoginIdAsLong());
            if (permissionCodeList.contains(infoCode)) {
                flag = false;
            }
        }
        if (flag && infoArticle.getStatus() != 2) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "页面不存在！");
        }
        return renderTemplate(sysChannel, articleId);
    }


    /**
     * 渲染并将数据动态加载到文字详细页模板
     *
     * @param sysChannel 栏目信息
     * @param articleId  文章ID
     * @return 渲染后的模板内容
     */
    private String renderTemplate(SysChannel sysChannel, Long articleId) {
        Long detailTemplate = sysChannel.getDetailTemplate();
        if (detailTemplate == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "页面不存在");
        }
        String templateUrl = this.sysTemplateService.getById(detailTemplate).getTemplateUrl();
        TemplateEngine dynamicTemplateEngine = templateEngine.getTemplateEngine();
        Context context = new Context();
        context.setVariable("channel", sysChannel);
        context.setVariable("articleId", articleId);
        context.setVariable("base", base);
        context.setVariable("channelTool", channelTool);
        context.setVariable("infoTool", infoTool);
        context.setVariable("sysTool", sysTool);
        context.setVariable("language", "zh-CN");
        context.setVariable("check", "check");
        this.staticHtmlService.setContextHeaderLink("zh-CN", context);
        // 使用动态模板引擎渲染模板
        return dynamicTemplateEngine.process(templateUrl, context);
    }


}
